const { networkInterfaces } = require("os");
const app = require("express")();

app.all("*", (req, res, next) => {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader("Access-Control-Allow-Headers", "content-type");
  next();
});

const server = app.listen(process.env.port, () => {
  let ip = networkInterfaces();
  for (k in ip) {
    for (i in ip[k]) {
      console.error(
        `listening on http://${ip[k][i].address}:${server.address().port}`
      );
    }
  }
  console.error("Waiting for target");
});

app.get("/", (req, res) => {
  res.send({
    code: 200,
  });
  let output = req.ip;
  console.error(`Got target! IP is ${output}`);
  if (process.env.simpleSSH) {
    if (req.query.user) {
      output = `${req.query.user}@${output}`;
    }
    if (req.query.port) {
      if (req.query.user) {
        output = `-p ${req.query.port} ${output}`;
      } else {
        output = `${output}:${req.query.port}`;
      }
    }
  } else {
    if (req.query.port) {
      output = `${output}:${req.query.port}`;
    }
  }
  console.log(output);
  process.exit();
});
